import requests
import re


def get_fund_name(fund_code):
    # 构造天天基金网详情页URL
    url = f"https://fund.eastmoney.com/{fund_code}.html"
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = 'utf-8'
        # 使用正则表达式提取基金名称
        # 在HTML中寻找 <title>基金名称 基金代码_天天基金网</title>
        pattern = r'<title>(.*?)' + fund_code + r'.*?</title>'
        match = re.search(pattern, response.text)
        if match:
            fund_name = match.group(1).strip()
            fund_name = re.split(r'[()]', fund_name)[0].strip()
            return fund_name
        else:
            return "未找到该基金"
    except Exception as e:
        return f"查询失败: {str(e)}"


if __name__ == "__main__":
    while 1:
        code = input('基金代码：')

        jj_name = get_fund_name(code)
        print(f"基金代码: {code}")
        print(f"基金名称: {jj_name}")
